import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import '../../core/services/tts_service.dart';
// Web平台导入
import '../../core/services/web_tts_service.dart'
    if (dart.library.io) '../../core/services/tts_service.dart';

class TTSControl extends StatefulWidget {
  final String text;
  final VoidCallback? onSpeakStart;
  final VoidCallback? onSpeakEnd;

  const TTSControl({
    super.key,
    required this.text,
    this.onSpeakStart,
    this.onSpeakEnd,
  });

  @override
  State<TTSControl> createState() => _TTSControlState();
}

class _TTSControlState extends State<TTSControl> with TickerProviderStateMixin {
  dynamic _ttsService;
  bool _isSpeaking = false;
  bool _isInitialized = false;
  bool _isWebPlatform = kIsWeb;

  // 动画控制器
  late AnimationController _waveController;
  late AnimationController _scaleController;
  late Animation<double> _waveAnimation;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();

    // 初始化动画控制器
    _waveController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _scaleController = AnimationController(
      duration: const Duration(milliseconds: 150),
      vsync: this,
    );

    // 创建波浪动画
    _waveAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _waveController, curve: Curves.easeInOut),
    );

    // 创建缩放动画
    _scaleAnimation = Tween<double>(begin: 1.0, end: 0.9).animate(
      CurvedAnimation(parent: _scaleController, curve: Curves.easeInOut),
    );

    print('🎬 动画控制器初始化完成: waveController=${_waveController.isAnimating}');
    _initializeTTS();
  }

  Future<void> _initializeTTS() async {
    try {
      // 根据平台选择TTS服务
      if (_isWebPlatform) {
        // Web平台尝试使用Web Speech API
        _ttsService = WebTTSService();
      } else {
        // 移动平台使用flutter_tts
        _ttsService = TTSService();
      }

      await _ttsService.initialize();
      setState(() {
        _isInitialized = true;
      });
    } catch (e) {
      print('❌ TTS初始化失败: $e');
      setState(() {
        _isInitialized = true; // 标记为已初始化，避免重复尝试
      });
    }
  }

  Future<void> _toggleSpeak() async {
    if (!_isInitialized) {
      await _initializeTTS();
    }

    if (_ttsService == null) return;

    if (_isSpeaking) {
      // 停止朗读
      await _ttsService.stop();
      _stopAnimations();
      setState(() {
        _isSpeaking = false;
      });
      widget.onSpeakEnd?.call();
    } else {
      // 开始朗读
      setState(() {
        _isSpeaking = true;
      });
      _startAnimations();
      widget.onSpeakStart?.call();

      try {
        await _ttsService.speak(widget.text);

        // 等待一段时间让动画显示，然后检查TTS状态
        await Future.delayed(const Duration(milliseconds: 100));

        // 如果TTS还在朗读，等待它完成
        while (_ttsService.isSpeaking && mounted) {
          await Future.delayed(const Duration(milliseconds: 100));
        }

        if (mounted) {
          _stopAnimations();
          setState(() {
            _isSpeaking = false;
          });
          widget.onSpeakEnd?.call();
        }
      } catch (e) {
        print('❌ TTS朗读失败: $e');
        if (mounted) {
          _stopAnimations();
          setState(() {
            _isSpeaking = false;
          });
          widget.onSpeakEnd?.call();
        }
      }
    }
  }

  void _startAnimations() {
    _waveController.repeat();
    _scaleController.forward();
  }

  void _stopAnimations() {
    _waveController.stop();
    _waveController.reset();
    _scaleController.reverse();
  }

  @override
  Widget build(BuildContext context) {
    final ColorScheme cs = Theme.of(context).colorScheme;

    // 检查是否支持TTS
    if (_ttsService != null && !_ttsService.isSupported) {
      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: cs.surfaceContainerHighest.withOpacity(0.5),
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: cs.outline.withOpacity(0.2), width: 1),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.volume_off_outlined,
              size: 20,
              color: cs.onSurface.withOpacity(0.5),
            ),
            const SizedBox(width: 8),
            Text(
              _isWebPlatform ? '浏览器不支持语音功能' : '语音功能仅支持移动设备',
              style: Theme.of(context).textTheme.labelMedium?.copyWith(
                color: cs.onSurface.withOpacity(0.5),
                fontSize: 12,
              ),
            ),
          ],
        ),
      );
    }

    return AnimatedBuilder(
      animation: _waveController,
      builder: (context, child) {
        return Transform.scale(
          scale: _isSpeaking ? _scaleAnimation.value : 1.0,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              color:
                  _isSpeaking
                      ? cs.primaryContainer.withOpacity(0.8)
                      : cs.surfaceContainerHighest,
              borderRadius: BorderRadius.circular(20),
              border: Border.all(
                color: _isSpeaking ? cs.primary : cs.outline.withOpacity(0.3),
                width: _isSpeaking ? 2 : 1,
              ),
              boxShadow:
                  _isSpeaking
                      ? [
                        BoxShadow(
                          color: cs.primary.withOpacity(0.3),
                          blurRadius: 8,
                          spreadRadius: 2,
                        ),
                      ]
                      : null,
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 语音图标（带动画）
                _isSpeaking
                    ? _buildWaveAnimation(cs)
                    : Icon(
                      Icons.volume_up_outlined,
                      size: 20,
                      color: cs.onSurface.withOpacity(0.7),
                    ),
                const SizedBox(width: 8),

                // 语音按钮
                GestureDetector(
                  onTap: _isInitialized ? _toggleSpeak : null,
                  child: Text(
                    _isSpeaking ? '停止朗读' : '朗读回复',
                    style: Theme.of(context).textTheme.labelMedium?.copyWith(
                      color:
                          _isInitialized
                              ? (_isSpeaking ? cs.primary : cs.onSurface)
                              : cs.onSurface.withOpacity(0.5),
                      fontWeight:
                          _isSpeaking ? FontWeight.w600 : FontWeight.normal,
                    ),
                  ),
                ),

                // 加载指示器
                if (!_isInitialized) ...[
                  const SizedBox(width: 8),
                  SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(cs.primary),
                    ),
                  ),
                ],
              ],
            ),
          ),
        );
      },
    );
  }

  // 构建波浪动画
  Widget _buildWaveAnimation(ColorScheme cs) {
    return AnimatedBuilder(
      animation: _waveController,
      builder: (context, child) {
        // 简单的测试动画 - 先确保基本功能工作
        final scale = 1.0 + _waveAnimation.value * 0.5;

        return Transform.scale(
          scale: scale,
          child: Icon(Icons.volume_up, size: 20, color: cs.primary),
        );
      },
    );
  }

  @override
  void dispose() {
    // 停止动画
    _waveController.dispose();
    _scaleController.dispose();

    // 组件销毁时停止朗读
    if (_ttsService != null) {
      _ttsService.stop();
    }
    super.dispose();
  }
}

// 语音设置面板
class TTSSettingsPanel extends StatefulWidget {
  final VoidCallback? onSettingsChanged;

  const TTSSettingsPanel({super.key, this.onSettingsChanged});

  @override
  State<TTSSettingsPanel> createState() => _TTSSettingsPanelState();
}

class _TTSSettingsPanelState extends State<TTSSettingsPanel> {
  dynamic _ttsService;
  double _speechRate = 1.0; // 提高默认语速
  double _pitch = 1.0; // 稍微提高音调
  double _volume = 1.0;
  bool _isWebPlatform = kIsWeb;

  @override
  void initState() {
    super.initState();
    _loadSettings();
  }

  Future<void> _loadSettings() async {
    try {
      // 根据平台选择TTS服务
      if (_isWebPlatform) {
        _ttsService = WebTTSService();
      } else {
        _ttsService = TTSService();
      }

      await _ttsService.initialize();

      print('🎤 TTS设置加载完成');
    } catch (e) {
      print('❌ TTS设置加载失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final ColorScheme cs = Theme.of(context).colorScheme;

    // 检查是否支持TTS
    if (_ttsService != null && !_ttsService.isSupported) {
      return Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: cs.surface,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: cs.outline.withOpacity(0.2)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              children: [
                Icon(
                  Icons.volume_off_outlined,
                  color: cs.onSurface.withOpacity(0.5),
                  size: 20,
                ),
                const SizedBox(width: 8),
                Text(
                  '语音设置',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: cs.surfaceContainerHighest.withOpacity(0.5),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                _isWebPlatform
                    ? '您的浏览器不支持Web Speech API，无法使用语音功能。'
                    : '语音功能仅支持移动设备（Android/iOS），在Web浏览器中无法使用。',
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                  color: cs.onSurface.withOpacity(0.7),
                ),
              ),
            ),
          ],
        ),
      );
    }

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: cs.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: cs.outline.withOpacity(0.2)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '语音设置',
            style: Theme.of(
              context,
            ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 16),

          // 语音速率
          _buildSliderSetting(
            label: '语音速率',
            value: _speechRate,
            min: 0.1,
            max: 1.0,
            divisions: 18,
            onChanged: (value) {
              setState(() {
                _speechRate = value;
              });
              _ttsService.setSpeechRate(value);
              widget.onSettingsChanged?.call();
            },
          ),

          const SizedBox(height: 16),

          // 音调
          _buildSliderSetting(
            label: '音调',
            value: _pitch,
            min: 0.5,
            max: 2.0,
            divisions: 15,
            onChanged: (value) {
              setState(() {
                _pitch = value;
              });
              _ttsService.setPitch(value);
              widget.onSettingsChanged?.call();
            },
          ),

          const SizedBox(height: 16),

          // 音量
          _buildSliderSetting(
            label: '音量',
            value: _volume,
            min: 0.0,
            max: 1.0,
            divisions: 10,
            onChanged: (value) {
              setState(() {
                _volume = value;
              });
              _ttsService.setVolume(value);
              widget.onSettingsChanged?.call();
            },
          ),
        ],
      ),
    );
  }

  Widget _buildSliderSetting({
    required String label,
    required double value,
    required double min,
    required double max,
    required int divisions,
    required ValueChanged<double> onChanged,
  }) {
    final ColorScheme cs = Theme.of(context).colorScheme;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(label, style: Theme.of(context).textTheme.bodyMedium),
            Text(
              value.toStringAsFixed(1),
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                color: cs.primary,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        SliderTheme(
          data: SliderTheme.of(context).copyWith(
            activeTrackColor: cs.primary,
            inactiveTrackColor: cs.outline.withOpacity(0.3),
            thumbColor: cs.primary,
            overlayColor: cs.primary.withOpacity(0.2),
          ),
          child: Slider(
            value: value,
            min: min,
            max: max,
            divisions: divisions,
            onChanged: onChanged,
          ),
        ),
      ],
    );
  }
}
